package org.jeecg.modules.param.station.controller;

import java.io.IOException;
import java.util.*;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;

import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.constant.BikeConstant;
import org.jeecg.modules.dto.station.StationRegisterRsp;
import org.jeecg.modules.param.pile.service.IBikePileService;
import org.jeecg.modules.param.station.entity.BikeStation;
import org.jeecg.modules.param.station.service.IBikeStationService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.param.station.vo.*;
import org.jeecg.modules.service.StationService;
import org.jeecg.modules.utils.page.PageInfo;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 网点设置
 * @Author: 月月鸟
 * @Date:   2021-05-19
 * @Version: V1.0
 */
@Api(tags="网点设置")
@RestController
@RequestMapping("/bikeStation/bikeStation")
@Slf4j
public class BikeStationController extends JeecgController<BikeStation, IBikeStationService> {
	@Autowired
	private IBikeStationService bikeStationService;
	@Autowired
	private IBikePileService bikePileService;

	 @Autowired
	 private StationService stationService;
	/**
	 * 分页列表查询
	 *
	 * @param bikeStation
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@ApiOperation(value="网点设置权限分页列表查询", notes="如有区域条件，传入id,id,id拼接字符串")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(BikeStation bikeStation,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		Page<BikeStation> stationPage = new Page<>(pageNo, pageSize);
		stationPage.setOptimizeCountSql(true);

		return  bikeStationService.stationList(stationPage, bikeStation);
	}


	 @GetMapping(value = "/getAdminList")
	 @ApiOperation(value = "网点设置-查询管理员信息（可传姓名和账号）", notes = "网点设置-查询管理员信息")
	 public Result<?> getAdminList(SysUserRe sysUserRe) {
		 return Result.OK(bikeStationService.getAdminList(sysUserRe));
	 }

	 /**
	  * 下发程序更新网点查询
	  *
	  * @param upSiteReq
	  * @param pageNo
	  * @param pageSize
	  * @param req
	  * @return
	  */
	 @ApiOperation(value="下发程序更新网点查询", notes="下发程序更新网点查询")
	 @GetMapping(value = "/upSiteList")
	 public Result<?> upSiteList(UpSiteReq upSiteReq,
								 @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								 HttpServletRequest req) {
		 Page<UpSiteRsp> objectPage = new Page<>(pageNo, pageSize);
		 if (StringUtils.isNotEmpty(upSiteReq.getAreaIds())){
		 	upSiteReq.setAreaArray(upSiteReq.getAreaIds().split(","));
		 }
		 List<UpSiteRsp> bikeStationPage1 = bikeStationService.upSiteList(pageNo,pageSize, upSiteReq);
		 objectPage.setRecords(bikeStationPage1);
		 objectPage.setTotal(bikeStationPage1.size());
	 	return Result.OK(objectPage);
	 }
	 /**
	  * 下发程序更新桩查询
	  *
	  * @param upSiteReq
	  * @param pageNo
	  * @param pageSize
	  * @param req
	  * @return
	  */
	 @ApiOperation(value="下发程序更新桩查询", notes="下发程序更新桩查询")
	 @GetMapping(value = "/upSitePileList")
	 public Result<?> upSitePileList(UpSiteReq upSiteReq,
								 @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								 HttpServletRequest req) {
		 Page<UpSiteRsp> objectPage = new Page<>(pageNo, pageSize);
		 if (StringUtils.isNotEmpty(upSiteReq.getAreaIds())){
			 upSiteReq.setAreaArray(upSiteReq.getAreaIds().split(","));
		 }
		 List<UpSiteRsp> bikeStationPage1 = bikeStationService.upSitePileList(pageNo,pageSize, upSiteReq);
		 objectPage.setRecords(bikeStationPage1);
		 objectPage.setTotal(bikeStationPage1.size());
		 return Result.OK(objectPage);
	 }
	 /**
	  * 网点借还车统计
	  *
	  * @param statisticalReq 网点编号，开始时间-结束时间
	  * @return
	  */
	 @ApiOperation(value = "网点借还车统计", notes = "网点借还车统计")
	 @GetMapping(value = "/statistical")
	 public Result<?> statistical(StatisticalReq statisticalReq,
								  @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
								  @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
								  HttpServletRequest req) {
		 //查询
		 QueryWrapper<BikeStation> stationQueryWrapper = new QueryWrapper<BikeStation>();
		 if (StringUtils.isNotEmpty(statisticalReq.getStationCode())){
			 stationQueryWrapper.like("code",statisticalReq.getStationCode());
		 }
		 stationQueryWrapper.orderByAsc("code");
		 Page<BikeStation> bikeStationPage = bikeStationService.page(new Page<>(pageNo, pageSize),stationQueryWrapper);
		 //查询数据转 StatisticalRsp 返回
		 List<StatisticalRsp> statistical = bikeStationService.statistical(statisticalReq,bikeStationPage.getRecords());
		 Page<StatisticalRsp> statisticalRspPage = new Page<>();
		 statisticalRspPage.setRecords(statistical);
		 statisticalRspPage.setTotal(bikeStationPage.getTotal());
		 return Result.OK(statisticalRspPage);
	 }
	 /**
	  * 网点借还车统计导出excel
	  *
	  * @param request
	  * @param statisticalReq
	  */
	 @RequestMapping(value = "/exportStatisticalXls")
	 public ModelAndView exportStatisticalXls(HttpServletRequest request,StatisticalReq statisticalReq) {
		 QueryWrapper<BikeStation> stationQueryWrapper = new QueryWrapper<BikeStation>();
		 if (StringUtils.isNotEmpty(statisticalReq.getStationCode())){
			 stationQueryWrapper.eq("code",statisticalReq.getStationCode());
		 }
		 stationQueryWrapper.orderByAsc("code");
		 List<BikeStation> list = bikeStationService.list(stationQueryWrapper);
		 return bikeStationService.exportStatisticalXls(request,statisticalReq,list);
	 }

	/**
	 *   添加
	 *
	 * @param bikeStation
	 * @return
	 */
	//@RequiresPermissions("station:add")
	@AutoLog(value = "网点设置-添加")
	@ApiOperation(value="网点设置-添加", notes="网点设置-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody BikeStation bikeStation,HttpServletRequest req) {

		return bikeStationService.add(bikeStation);
	}
	 /**
	  * 网点模糊列表
	  *
	  * @param code name
	  * @return
	  */
	 @ApiOperation(value="网点模糊列表", notes="网点模糊列表")
	 @GetMapping(value = "/likeList")
	 public Result<?> likeList(@RequestParam(value = "code", required = false) String code
			 , @RequestParam(value = "name", required = false) String name
			 , @RequestParam(value = "areaId", required = false) String areaId) {
		 QueryWrapper<BikeStation> wrapper = new QueryWrapper<>();
		 wrapper.select("id","name","code","address");
		 if (StringUtils.isNotEmpty(code)){
			 wrapper.like("code",code);
		 }
		 if (StringUtils.isNotEmpty(name)){
			 wrapper.like("name",name);
		 }
		 if (StringUtils.isNotEmpty(areaId)){
		 	wrapper.like("area_id",areaId);
		 }
		 List<BikeStation> list = bikeStationService.list(wrapper);
		 return Result.OK(list);
	 }
	/**
	  *  编辑
	  *
	  * @param bikeStation
	  * @return
	  */
	 //@RequiresPermissions("station:edit")
	 @AutoLog(value = "网点设置-编辑",operateType = 3)
	 @ApiOperation(value="网点设置-编辑", notes="网点设置-编辑")
	 @PutMapping(value = "/edit")
	 public Result<?> edit(@RequestBody BikeStation bikeStation,HttpServletRequest req) {
		 Result<?> edit = bikeStationService.edit(bikeStation);
		 String message = edit.getMessage();
		 if (message.equals("编辑成功")){
			 StationRegisterRsp stationRegisterRsp = new StationRegisterRsp();
			 stationRegisterRsp.setStationCode(bikeStation.getCode());
			 stationService.pileRegister(stationRegisterRsp);
		 }
		 return edit;
	 }


	@AutoLog(value = "网点设置-锁定与解锁",operateType = 3)
	@ApiOperation(value="锁定与解锁", notes="锁定与解锁")
	@PutMapping(value = "/lock")
	public Result<?> lockStation(@RequestBody StationLock stationLock){
		return bikeStationService.lockStation(stationLock);
	}
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	//@RequiresPermissions("station:delete")
	@AutoLog(value = "网点设置-通过id删除")
	@ApiOperation(value="网点设置-通过id删除", notes="网点设置-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		return bikeStationService.deleteById(id);
	}
	 /**
	  *   通过id 清除注册状态
	  * @param id
	  * @return
	  */
	 @AutoLog(value = "网点设置-清除注册状态",operateType =3)
	 @ApiOperation(value="网点设置-清除注册状态", notes="网点设置-清除注册状态")
	 @DeleteMapping(value = "/clearRegister")
	 public Result<?> clearRegister(@RequestParam(name="id",required=true) String id) {
		 return bikeStationService.clearRegister(id);
	 }

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "网点设置-批量删除")
	@ApiOperation(value="网点设置-批量删除", notes="网点设置-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		List<String> strings = Arrays.asList(ids.split(","));
		this.bikeStationService.removeByIds(strings);
		bikeStationService.delPile(strings);
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@ApiOperation(value="网点设置-通过id查询", notes="网点设置-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		BikeStation bikeStation = bikeStationService.getById(id);
		if(bikeStation==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(bikeStation);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param bikeStation
    */
	@ApiOperation(value="网点设置-导出excel", notes="网点设置-导出excel")
	@RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, BikeStation bikeStation) {
        return bikeStationService.exportXls(request,bikeStation);
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @AutoLog(value ="网点设置-导入")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			try {
				List<BikeStation> list = ExcelImportUtil.importExcel(file.getInputStream(), BikeStation.class, params);
				//update-begin-author:taoyan date:20190528 for:批量插入数据
				long start = System.currentTimeMillis();
				String err = null;
				// 月月鸟 ： 添加判断覆盖或添加，避免SQLIntegrityConstraintViolationException ID重复覆盖异常
				for (int i = 0 ; i<list.size(); i++){
					BikeStation tb = list.get(i);
					String num = tb.getCode();
					String s = checkImportExcel(tb);
					if (StringUtils.isNotEmpty(s)){
						if (err==null){
							err= "网点："+num+"-"+s;
						}else {
							err=err+"网点："+num+"-"+s;
						}
					}
				}
				if (StringUtils.isNotEmpty(err)){
					return Result.error("文件导入失败:"+err);
				}
				for (int i = 0 ; i<list.size(); i++){
					BikeStation tb = list.get(i);
					BikeStation bikeStation = bikeStationService.getStationByCode(tb.getCode());

					if (bikeStation==null){
						tb.setId(UUID.randomUUID().toString().replace("-","")	);
						if (tb.getEnableTime()==null){
							if (tb.getStatus().equals(BikeConstant.y_n_yes)){
								tb.setEnableTime(new Date());
							}
						}
						if (StringUtils.isEmpty(tb.getIsRegister())){
							tb.setIsRegister(BikeConstant.y_n_no);
						}
						if (StringUtils.isEmpty(tb.getIsManager())){
							tb.setIsManager(BikeConstant.y_n_no);
						}
						if (StringUtils.isEmpty(tb.getLongitude())){
							tb.setLongitude("0.0");
						}
						if (StringUtils.isEmpty(tb.getLatitude())){
							tb.setLatitude("0.0");
						}
						bikeStationService.save(tb);
						bikeStationService.addPile(tb);
						if (StringUtils.isEmpty(tb.getManageName())){
							bikeStationService.addAreaUser(null,tb.getId());
						}else {
							bikeStationService.addAreaUser(tb.getManageName(),tb.getId());
						}
					}else {
						BikeStation newStation = stationToNewStation(tb,bikeStation);
						bikeStationService.updateById(newStation);
						bikeStationService.addPile(bikeStation);
						if (StringUtils.isEmpty(tb.getManageName())){
							bikeStationService.addAreaUser(null,bikeStation.getId());
						}else {
							bikeStationService.addAreaUser(tb.getManageName(),bikeStation.getId());
						}
					}
				}
				log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				return Result.OK("文件导入成功！数据行数："+list.size(),err);
			} catch (Exception e) {
				log.error(e.getMessage(), e);
				return Result.error("文件导入失败:" + e.getMessage());
			} finally {
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return Result.error("文件导入失败！");
	}

	 private String checkImportExcel(BikeStation tb) {
		 String err = "";
		 //校验内容
		 if (StringUtils.isEmpty(tb.getName())
				 || StringUtils.isEmpty(tb.getAreaCode())
				 || StringUtils.isEmpty(tb.getStatus())
				 || StringUtils.isEmpty(tb.getIsLocation())) {
			 return err + "网点编号,网点名称,是否自动获取定位,状态是必填数据;";
		 }else {
		 	tb.setName(tb.getName().replace(" ",""));
		 	tb.setAreaCode(tb.getAreaCode().replace(" ",""));
		 }
		 if (tb.getName().length()>16){
		 	return err+"[网点名称]不能超过16位";
		 }
		 if (tb.getCode().length()>5){
			 return err+"[网点编号]不能超过5位";
		 }
		 if (StringUtils.isNotEmpty(tb.getAreaCode())) {
			 String areaId = bikeStationService.getAreaId(tb.getAreaCode());
			 if (StringUtils.isNotEmpty(areaId)) {
				 tb.setAreaId(areaId);
			 } else {
				 return err+"[区域编号]不存在；";
			 }
		 }
		 ////校验经纬度
		 //if (StringUtils.isEmpty(tb.getLongitude())) {
			// tb.setLongitude("0.0");
		 //} else {
			// String pattern = "/^(\\-|\\+)?(((\\d|[1-9]\\d|1[0-7]\\d|0{1,3})\\.\\d{0,10})|(\\d|[1-9]\\d|1[0-7]\\d|0{1,3})|180\\.0{0,6}|180)$/";
			// boolean matches = Pattern.matches(pattern, tb.getLongitude());
			// if (!matches) {
			//	 return err + "[经度]格式错误；";
			// }
		 //}
		 //if (StringUtils.isEmpty(tb.getLatitude())) {
			// tb.setLatitude("0.0");
		 //} else {
			// String pattern = "/^(\\-|\\+)?([0-8]?\\d{1}\\.\\d{0,10}|90\\.0{0,15}|[0-8]?\\d{1}|90)$/";
			// boolean matches = Pattern.matches(pattern, tb.getLatitude());
			// if (!matches) {
			//	 return err + "[纬度]格式错误；";
			// }
		 //}
		 if (StringUtils.isNotEmpty(tb.getStatus())&&!tb.getStatus().equals("1") && !tb.getStatus().equals("0")) {
			 return err + "[状态]未识别到对应参数；";
		 }
		 if (StringUtils.isNotEmpty(tb.getIsRegister())) {
			 if (!tb.getIsRegister().equals("1") && !tb.getIsRegister().equals("0")) {
				 return err + "[是否注册]未识别到对应参数；";
			 }
		 }else {
		 	tb.setIsRegister(BikeConstant.y_n_no);
		 }
		 if (StringUtils.isNotEmpty(tb.getIsManager())) {
			 if (!tb.getIsManager().equals("1") && !tb.getIsManager().equals("0")) {
				 return err + "[管理卡是否下发成功]未识别到对应参数；";
			 }
		 }else {
		 	tb.setIsManager(BikeConstant.y_n_no);
		 }
		 if (StringUtils.isNotEmpty(tb.getIsLock())) {
			 if (!tb.getIsLock().equals("1")&&!tb.getIsLock().equals("0")){
				 return err+"[是否锁定]未识别到对应参数；";
			 }
		 }else {
		 	tb.setIsLock(BikeConstant.y_n_no);
		 }
		 if (StringUtils.isNotEmpty(tb.getIsLocation())&&!tb.getIsLocation().equals("1")&&!tb.getIsLocation().equals("0")){
			 return err+"[是否自动获取定位]未识别到对应参数；";
		 }
		 if (StringUtils.isEmpty(tb.getAddress())){
			 return err+"[网点地址]缺少网点地址；";
		 }
		 return err;
	 }


	 private BikeStation stationToNewStation(BikeStation join, BikeStation data) {
		 if (StringUtils.isNotEmpty(join.getName())){
			 data.setName(join.getName());
		 }
		 if (StringUtils.isNotEmpty(join.getAddress())){
			 data.setAddress(join.getAddress());
		 }
		 if (join.getPileCount()>data.getPileCount()){
			 data.setPileCount(join.getPileCount());
		 }
		 if (StringUtils.isNotEmpty(join.getAreaId())){
			 data.setAreaId(join.getAreaId());
		 }
		 if (StringUtils.isNotEmpty(join.getLongitude())){
			 join.getLongitude().replace(" ","");
			 data.setLongitude(join.getLongitude());
		 }
		 if (StringUtils.isNotEmpty(join.getLatitude())){
			 join.getLatitude().replace(" ","");
			 data.setLatitude(join.getLatitude());
		 }
		 if (StringUtils.isNotEmpty(join.getManageName())){
			 data.setManageName(join.getManageName());
		 }
		 if (StringUtils.isNotEmpty(join.getManagePhone())){
			 data.setManagePhone(join.getManagePhone());
		 }
		 if (StringUtils.isNotEmpty(join.getStatus())){
			 data.setStatus(join.getStatus());
		 }
		 if (StringUtils.isNotEmpty(join.getIsRegister())){
			 data.setIsRegister(join.getIsRegister());
		 }
		 if (StringUtils.isNotEmpty(join.getIsManager())){
			 data.setIsManager(join.getIsManager());
		 }
		 if (StringUtils.isNotEmpty(join.getIsLock())){
			 data.setIsLock(join.getIsLock());
		 }
		 if (StringUtils.isNotEmpty(join.getLockCause())){
			 data.setLockCause(join.getLockCause());
		 }
		 if (join.getEnableTime()!=null){
		 	data.setEnableTime(join.getEnableTime());
		 }
		 if (StringUtils.isNotEmpty(join.getIsLocation())){
		 	data.setIsLocation(join.getIsLocation());
		 }
    	return data;
	 }
 }
